<template>
  <div v-if="is_info">
    <template v-for="row in this_config">
      <el-switch :model-value="is_on(row.unit)" :size="size" inline-prompt :inactive-text="row.text" :active-text="row.text"></el-switch>
    </template>
  </div>
  <div v-else class="form_item-radio_switch">
    <input type="hidden" :name="name" :value="value">
    <template v-for="(row,i) in this_config">
      <el-switch v-model="this_value[i]" :size="size" inline-prompt :inactive-text="row.text" :active-text="row.text" @change="update_value"></el-switch>
    </template>
  </div>
</template>

<script>
import {decode_config} from "@/js/s94_tool.js";

export default {
  _title_: '开关组',
  _can_config_: true,
  name: "radio_switch",
  props: ['name', 'value', 'config', 'is_info', 'size', 'is_list'],
  emits: ['update:value', 'change'],
  data(){
    return {
      need_display: true,
      this_value: [],
    }
  },
  methods: {
    update_value(){
      let v = 0;
      this.this_value.forEach((is_on, i)=>{
        if (is_on) v += Math.pow(2,i);
      })
      this.need_display = false;
      setTimeout(()=>{this.need_display = true;},5);
      this.$emit('update:value', v);
      this.$emit('change', v);
    },
    is_on(unit){
      return !!(parseInt(this.value) & parseInt(unit));
    },
    display_value(config){
      this.this_value = [];
      config.forEach((row,i)=>{
        this.this_value[i] = this.is_on(row.unit);
      })
    },
  },
  watch: {
    value(){
      if (!this.need_display) return;
      this.display_value(this.this_config);
    },
  },
  computed: {
    this_config(){
      let res = [];
      let config = decode_config(this.config);
      config.forEach((row,i)=>{
        let unit = Math.pow(2,i);
        res.push({
          text: row.content,
          unit: unit,
        })
      })
      this.display_value(res);
      return res;
    },
  },
  mounted() {
    this.display_value(this.this_config);
  }
}
</script>

<style scoped>

</style>